import * as THREE from 'three'

/**
 * 通过经纬度转换成三维坐标
 * @param radius number
 * @param longitude string | number
 * @param latitude string | number
 */
export function lon2xyz (radius: number, longitude: string | number, latitude: string | number) {
  const lat = Number(latitude) * (Math.PI / 180)
  // three.js坐标系z坐标轴对应经度-90度，而不是90度
  const lon = -Number(longitude) * (Math.PI / 180)
  // const lon = (Number(longitude) + 90) * (Math.PI / 180)

  // 经纬度坐标转球面坐标计算公式
  return { x: radius * Math.cos(lat) * Math.cos(lon), y: radius * Math.sin(lat), z: radius * Math.cos(lat) * Math.sin(lon) }
}
/**
 * 当前元素中心-坐标原点（XOY）
 * @param event MouseEvent
 * @param layer HTMLElement
 * @returns State { x: number, y: number }
 */
export function onPointerMove (event: MouseEvent, layer?: HTMLElement) {
  if (layer) {
    const { x, y, height, width } = layer.getBoundingClientRect()
    // 将鼠标位置归一化为设备坐标: x 和 y 方向的取值范围是 (-1 to +1)
    return { x: ((event.clientX - x) / width) * 2 - 1, y: -((event.clientY - y) / height) * 2 + 1 }
  } else {
    const { innerWidth, innerHeight } = window
    // 将鼠标位置归一化为设备坐标: x 和 y 方向的取值范围是 (-1 to +1)
    return { x: (event.clientX / innerWidth) * 2 - 1, y: -(event.clientY / innerHeight) * 2 + 1 }
  }
}

export function getIntersects (event: MouseEvent, scene: THREE.Scene, camera: THREE.Camera, layer: HTMLElement) {
  const raycaster = new THREE.Raycaster()
  // 将鼠标位置归一化为设备坐标
  const state = onPointerMove(event, layer)
  const pointer = new THREE.Vector2(state.x, state.y)
  // 通过摄像机和鼠标位置更新射线
  raycaster.setFromCamera(pointer, camera)
  // 计算物体和射线的焦点
  return raycaster.intersectObject(scene)
}
